package com.zhike.api.controller.user;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zhike.common.dto.CollectAddDTO;
import com.zhike.common.dto.CollectDeleteDTO;
import com.zhike.common.dto.CollectQueryDTO;
import com.zhike.common.dto.R;
import com.zhike.common.repository.Collect;
import com.zhike.common.vo.UserInfo4Cache;
import com.zhike.service.collect.ICollectRepository;
import com.zhike.service.system.ISystemService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@RestController
@RequestMapping("api/zkim/user/collect")
@Api(tags = "用户收藏夹模块")
public class CollectController {

    @Autowired
    private ICollectRepository collectRepository;

    @Autowired
    private ISystemService systemService;

    @ApiOperation(value = "添加收藏")
    @PostMapping("add")
    public R<Boolean> add(@Validated @RequestBody CollectAddDTO dto) {
        UserInfo4Cache uc = systemService.getUserInfo();

        Collect c = collectRepository.findAndModify(dto.getMessageId(), uc.getFakeUid());
        if (null == c) {
            Collect collect = null;
            collect = new Collect();
            collect.setMessageId(dto.getMessageId());
            collect.setSenderUid(dto.getSenderUid());
            collect.setTimestamp(new Date());
            collect.setUid(uc.getFakeUid());
            collect.setType(dto.getCollectType());
            collect.setContent(dto.getContent());
            return R.success(collectRepository.saveCollect(collect));
        }
        return R.success(Boolean.TRUE);
    }

    @ApiOperation(value = "收藏列表")
    @PostMapping("list")
    public R<List<Collect>> list(@Validated @RequestBody CollectQueryDTO dto) {
        UserInfo4Cache uc = systemService.getUserInfo();
        return R.success(collectRepository.findCollects(uc.getFakeUid(), dto.getCollectType()));
    }

    @ApiOperation(value = "删除收藏")
    @PostMapping("delete")
    public R<Boolean> delete(@Validated @RequestBody CollectDeleteDTO dto) {
        return R.success(collectRepository.deleteCollect(dto.getIds()));
    }

}
